import { Commit } from 'vuex'
import axios, { AxiosRequestConfig } from 'axios'
import store from '@/store'

// 拦截器 https://github.com/axios/axios#interceptors
axios.interceptors.request.use(function (config) {
  store.commit('setLoading', true)
  store.commit('setError', { status: false, message: '' })
  return config;
});
axios.interceptors.response.use(function (response) {
  store.commit('setLoading', false)
  return response;
}, function (err) {
  const { error } = err.response.data
  store.commit('setError', { status: false, message: error })
  store.commit('setLoading', false)
  return Promise.reject(error);
});

export const asyncAndCommit = async (
  url: string,
  mutation: string,
  commit: Commit,
  config: AxiosRequestConfig
    = { method: 'get' }
) => {
  const { data } = await axios(url, config)

  // 提交载荷（Payload）
  commit(mutation, data)

  return data
}